<template>
   <h1>ref全家桶</h1>
    <div>ref:{{cs}}</div>
    <button @click="changeref">改ref</button>
    <button @click="isref">判断ref</button>
    <div>shallowRef:{{cs2}}</div>
    <button @click="changeshallowRef">改shallowRef</button>
    <button @click="changeshallowRef2">深改shallowRef</button>
    <button @click="changetriggerRef">triggerRef</button>

    <h2></h2>
    <button @click="changeshallowRef3">ref修改和shallowRef修改放一起，相互影响了</button>
    <h3>customRef:{{obj}}</h3>
    <button @click="changecustom">修改customRef</button>
    <div ref="dom">我是dom</div>
</template>

<script setup lang="ts">
import {ref,isRef,shallowRef,triggerRef,customRef} from 'vue'
    const cs=ref({name:'chensheng'})
    const cs2=shallowRef({name:'chensheng2'})

    const changeref=() => {
        cs.value.name='ChenSheng'
    }
    const isref=() => {
        console.log(isRef(cs))
    }
    const changeshallowRef=() => {
        cs2.value.name='ChenSheng2' //界面上不会改版
    }
    const changeshallowRef2=() => {
        cs2.value={name:'ChenSheng2'} //界面上会改版
    }
    const changetriggerRef=() => {
        cs2.value.name='ChenSheng2' //界面上不会改版
        triggerRef(cs2) //调用triggerRef导致修改
    }
    const changeshallowRef3=() => {
        cs.value.name='ChenSheng'
        cs2.value.name='ChenSheng2' //界面上不会改版
        //放一起，影响了  导致shallowRef会修改
    }
    let timer:any
    function MyRef<T>(value:T){
        return customRef(((track, trigger) => {
            return{
                get(){
                    track()
                    return value
                },
                set(newVal){
                    clearTimeout(timer)
                    timer=setTimeout(() => {
                        console.log('修改触发了')
                        timer=null
                        value=newVal
                        trigger()
                    },500)
                }
            }
        }))
    }
    const obj=MyRef<string>('chensheng ref')
    const changecustom=() => {
        obj.value='chensheng ref 修改了'
        console.log(dom.value?.innerText)

    }
    const dom=ref<HTMLDivElement>()
    console.log(dom.value?.innerText)
</script>

<style scoped>

</style>